<?php

namespace app\xs_wxapp\controller\web;

use xsframe\base\AdminBaseController;
use xsframe\exception\ApiException;
use xsframe\facade\service\DbServiceFacade;
use xsframe\util\ArrayUtil;
use xsframe\util\FileUtil;

class Release extends AdminBaseController
{
    public function push(): \think\response\View
    {
        if ($this->request->isPost()) {
            $uniacid = intval($this->params['uniacid']);
            $apiRoot = trim($this->params['apiroot']);
            $module = trim($this->params['identifie']);
            $paths = $this->params['paths'] ?? [];

            if (empty($paths)) {
                throw new ApiException("请选择要下载的文件目录");
            }

            // 定义 ZIP 文件名
            $zipFilePath = IA_ROOT . "/runtime/zip/";
            FileUtil::mkDirs($zipFilePath);
            $zipFilename = $zipFilePath . "{$module}.zip";

            // 创建一个 ZipArchive 对象
            $zip = new \ZipArchive();

            // 如果 ZIP 文件已存在，则删除它
            if (file_exists($zipFilename)) {
                unlink($zipFilename);
            }

            // 打开 ZIP 文件以写入
            if ($zip->open($zipFilename, \ZipArchive::CREATE | \ZipArchive::OVERWRITE) !== true) {
                exit("无法打开 <$zipFilename>\n");
            }

            $fileToModifyRelativePath = 'siteInfo.js';
            $modifiedContent = <<<EOF
let siteInfo = {
	'uniacid': typeof uniacid != 'undefined' ? uniacid : {$uniacid},
	'version': typeof version != 'undefined' ? version : 1.0,
	'module': typeof moduleName != 'undefined' ? moduleName : '{$module}',
	'apiroot': typeof apiroot != 'undefined' ? apiroot : (process.env.NODE_ENV === 'development' ? '{$apiRoot}' : '{$apiRoot}'),
};
module.exports = siteInfo;
EOF;

            foreach ($paths as $path) {
                $this->addFolderToZip($zip, $path);

                // 处理需要修改的文件
                $fileToModifyFullPath = realpath($path . DIRECTORY_SEPARATOR . $fileToModifyRelativePath);
                if (file_exists($fileToModifyFullPath)) {
                    // 获取文件的相对路径（用于 ZIP 归档中的路径）
                    $relativePathInZip = $fileToModifyRelativePath;

                    // 添加修改后的文件内容到 ZIP
                    $zip->addFromString($relativePathInZip, $modifiedContent);
                }
            }

            // 关闭 ZIP 文件
            $zip->close();

            // 写入的过程中应该将接口中的参数更改了 TODO

            $this->success(['url' => webUrl('release/download', ['name' => $module, 'path' => $zipFilename])]);
        }

        $appList = DbServiceFacade::name('sys_account_modules')->getAll(['uniacid' => $this->uniacid, 'deleted' => 0], "*", "displayorder asc");
        $list = [];
        foreach ($appList as $key => &$item) {
            $moduleInfo = DbServiceFacade::name('sys_modules')->getInfo(['identifie' => $item['module']], "name,wxapp_support");
            if ($moduleInfo['wxapp_support']) {
                $item['name'] = $moduleInfo['name'];
                $list[] = $item;
            }
        }

        $result = [
            'appList' => $list
        ];
        return $this->template('push', $result);
    }

    public function download(): \think\response\File
    {
        $zipPath = trim($this->params['path'] ?? '');
        $zipName = trim($this->params['name'] ?? '');
        return download($zipPath, $zipName);
    }

    public function getFolderList(): \think\response\Json
    {
        $module = trim($this->params['module']);

        $modulePath = IA_ROOT . '/app/' . $module;

        $fileList = [];

        $isWxappFolder = $modulePath . "/packages/" . "wxapp";
        if (is_dir($isWxappFolder) && is_file($isWxappFolder . "/" . "siteInfo.js")) {
            $fileList[] = [
                'name' => basename($isWxappFolder),
                'path' => $isWxappFolder,
            ];
        }

        $isSourceFolder = $modulePath . "/packages/" . "source";

        foreach (glob($isSourceFolder . "/*") as $folderPath) {
            if (is_file($folderPath . "/" . "siteInfo.js")) {
                $fileList[] = [
                    'name' => basename($folderPath),
                    'path' => $folderPath,
                ];
            }
        }

        if (empty($fileList)) {
            throw new ApiException("该应用暂无小程序发布包");
        }

        return json([
            'list' => $fileList
        ]);
    }

    private function addFolderToZip($zip, $folderName, $basePath = '')
    {
        $folder = realpath($folderName);

        if (is_dir($folder)) {
            $folder = rtrim($folder, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
            $base = rtrim($basePath, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;

            $files = new \RecursiveIteratorIterator(
                new \RecursiveDirectoryIterator($folder),
                \RecursiveIteratorIterator::LEAVES_ONLY
            );

            foreach ($files as $name => $file) {
                // 跳过目录（它们会在添加文件时自动创建）
                if (!$file->isDir()) {
                    // 获取文件的相对路径
                    $filePath = $file->getRealPath();
                    $relativePath = substr($filePath, strlen($folder));

                    // 将文件添加到 ZIP，使用相对路径（相对于 $basePath）
                    $zip->addFile($filePath, $base . $relativePath);
                }
            }
        } else {
            // 如果提供的不是一个文件夹，则尝试直接添加文件（这里可以根据需要修改）
            // 注意：这个分支在当前的上下文中不会被执行，因为我们只传递文件夹路径
        }
    }
}
